<!doctype html>
<html lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8">
    <meta name="baidu-site-verification" content="dIcXMeY8Ya">
    
    <title>Class源码 | blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
    <meta name="keywords" content="Jim, 服务端, Java, Java开发">
    <meta name="description" content="Jim个人学习记录">

    
    <link rel="alternative" href="/atom.xml" title="blog" type="application/atom+xml">
    
    
    <link rel="shortcut icon" href="/favicon.ico">
    
    <link rel="stylesheet" href="/css/style.css">
    <!--[if lt IE 9]>
    <script src="/js/html5.js"></script>
    <![endif]-->
    
<script>
    var _hmt = _hmt || [];
    (function() {
        var hm = document.createElement("script");
        hm.src = "//hm.baidu.com/hm.js?fd459238242776d173cdc64918fb32f2";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>


</head>
</html>
<body class="home">
    <!--[if lt IE 9]>
    <div class="browsehappy">
        当前网页 <strong>不支持</strong>
        你正在使用的浏览器. 为了正常的访问, 请 <a href="http://browsehappy.com/">升级你的浏览器</a>.
    </div>
    <![endif]-->

    <!-- 博客头部 -->
    <header class="header">
    <section class="container header-main">
        <div class="logo">
            <a href="/">
                <div class="cover">
                    <span class="name">blog</span>
                    <span class="description"></span>
                </div>
            </a>
        </div>
        <div class="dropnav icon-paragraph-justify" id="JELON__btnDropNav"></div>
        <ul class="menu hidden" id="JELON__menu">
            
            <li rel="/2019/07/11/Class源码/index.html" class="item ">
                <a href="/" title="首页" class="icon-home">&nbsp;首页</a>
            </li>
            
            <li rel="/2019/07/11/Class源码/index.html" class="item ">
                <a href="/about/" title="关于" class="icon-about">&nbsp;关于</a>
            </li>
            
            <li rel="/2019/07/11/Class源码/index.html" class="item ">
                <a href="/comment/" title="留言" class="icon-comment">&nbsp;留言</a>
            </li>
            
        </ul>
        <div class="profile clearfix">
            <div class="feeds fl">
                
                
                <p class="links">
                    
                        <a href="https://github.com/starryming" target="_blank">Github</a>
                        |
                    
                        <a href="http://ljmstarry.gitee.io" target="_blank">Hosted by Coding Pages</a>
                        
                    
                </p>
                <p class="sns">
                    
                        <a href="http://weibo.com/" class="sinaweibo" target="_blank"><b>■</b> 新浪微博</a>
                    
                        <a href="https://www.facebook.com/" class="qqweibo" target="_blank"><b>■</b> Facebook</a>
                    
                    <a href="javascript: void(0);" class="wechat">
                        <b>■</b>
                        公众号
                        <span class="popover">
                            <img src="/img/wechat_mp.jpg" width="120" height="120" alt="我的微信订阅号">
                            <i class="arrow"></i>
                        </span>
                    </a>
                </p>
                
            </div>
            <div class="avatar fr">
                <img src="/img/timg.jpg" alt="avatar" title="Jim">
            </div>
        </div>
    </section>
</header>


    <!-- 博客正文 -->
    <div class="container body clearfix">
        <section class="content">
            <div class="content-main widget">
                <!-- 文章页 -->
<!-- 文章 -->
<article class="post article">
    <header class="text-center">
        <h3 class="post-title"><span>Class源码</span></h3>
    </header>
    <p class="post-meta text-center">
        Jim 发表于
        <time datetime="2019-07-11T05:47:08.000Z">2019-07-11</time>
    </p>
    <div class="post-content">
        <h3 id="Class源码"><a href="#Class源码" class="headerlink" title="Class源码"></a>Class源码</h3><p>1.Class.getDeclaredField / Class.getField</p>
<p>2.class.newInstance()</p>
<p>3.class.getConstructor() \ class.getDeclaredConstructor()</p>
<a id="more"></a>
<h5 id="1、【Class-getDeclaredField】与【Class-getField-】"><a href="#1、【Class-getDeclaredField】与【Class-getField-】" class="headerlink" title="1、【Class.getDeclaredField】与【Class.getField 】"></a>1、【<strong>Class.getDeclaredField</strong>】与【<strong>Class.getField </strong>】</h5><p>​        </p>
<blockquote>
<ul>
<li><p>getDeclaredFiled 仅能获取类本身的属性成员（包括私有、共有、保护） </p>
</li>
<li><p>getField 仅能获取类(及其父类可以自己测试) public属性成员</p>
</li>
</ul>
<p>=&gt; 反射机制，在获取父类的私有属性时，要通过getSuperclass的之后再通过getDeclaredFiled获取</p>
</blockquote>
<blockquote>
<p>​    与之对应的获取 <strong>所有</strong> 公共成员字段 和 私有成员字段 的方法为 <strong>Class.getFields()</strong> 和 <strong>Class.getDeclaredFields()</strong></p>
</blockquote>
<ul>
<li>1）Class.getDeclaredField</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CallerSensitive</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Field <span class="title">getDeclaredField</span><span class="params">(String name)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> NoSuchFieldException, SecurityException </span>&#123;</span><br><span class="line">        <span class="comment">// 安全管理器校验</span></span><br><span class="line">        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), <span class="keyword">true</span>);</span><br><span class="line">        Field field = searchFields(privateGetDeclaredFields(<span class="keyword">false</span>), name);</span><br><span class="line">        <span class="keyword">if</span> (field == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchFieldException(name);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> field;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>字段、方法或构造函数的获取</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">   * Helpers for fetchers of one field, method, or constructor</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Field <span class="title">searchFields</span><span class="params">(Field[] fields, String name)</span> </span>&#123;</span><br><span class="line">       String internedName = name.intern();</span><br><span class="line">       <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; fields.length; i++) &#123;</span><br><span class="line">           <span class="keyword">if</span> (fields[i].getName() == internedName) &#123;</span><br><span class="line">               <span class="comment">// copyField深度克隆 杜绝了这个类的字段操作对其他的字段的影响</span></span><br><span class="line">               <span class="keyword">return</span> getReflectionFactory().copyField(fields[i]);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>【单例模式 - 懒汉式静态内部类】 -  第一次用到时再创建 后续访问直接返回:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Fetches the factory for reflective objects</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ReflectionFactory <span class="title">getReflectionFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="comment">// 懒汉模式</span></span><br><span class="line">       <span class="keyword">if</span> (reflectionFactory == <span class="keyword">null</span>) &#123;</span><br><span class="line">           reflectionFactory =</span><br><span class="line">               java.security.AccessController.doPrivileged</span><br><span class="line">               	<span class="comment">// 静态内部类模式</span></span><br><span class="line">                   (<span class="keyword">new</span> sun.reflect.ReflectionFactory.GetReflectionFactoryAction());</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> reflectionFactory;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> ReflectionFactory reflectionFactory;</span><br></pre></td></tr></table></figure>
<ul>
<li>2）getFields</li>
</ul>
<blockquote>
<p>class.getFileds如何拿到父类和以及接口的公开的字段？我们可以借用哪些思想？</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CallerSensitive</span></span><br><span class="line">    <span class="keyword">public</span> Field[] getFields() <span class="keyword">throws</span> SecurityException &#123;</span><br><span class="line">        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), <span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span> copyFields(privateGetPublicFields(<span class="keyword">null</span>));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> Field[] privateGetPublicFields(Set&lt;Class&lt;?&gt;&gt; traversedInterfaces) &#123;</span><br><span class="line">        checkInitted();</span><br><span class="line">        Field[] res;</span><br><span class="line">        ReflectionData&lt;T&gt; rd = reflectionData();</span><br><span class="line">        <span class="keyword">if</span> (rd != <span class="keyword">null</span>) &#123;</span><br><span class="line">            res = rd.publicFields;</span><br><span class="line">            <span class="keyword">if</span> (res != <span class="keyword">null</span>) <span class="keyword">return</span> res;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// No cached value available; compute value recursively.</span></span><br><span class="line">        <span class="comment">// Traverse in correct order for getField().</span></span><br><span class="line">        List&lt;Field&gt; fields = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">if</span> (traversedInterfaces == <span class="keyword">null</span>) &#123;</span><br><span class="line">            traversedInterfaces = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 1.Local fields 当前类字段加载</span></span><br><span class="line">        Field[] tmp = privateGetDeclaredFields(<span class="keyword">true</span>);</span><br><span class="line">        addAll(fields, tmp);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2.Direct superinterfaces, recursively</span></span><br><span class="line">        <span class="keyword">for</span> (Class&lt;?&gt; c : getInterfaces()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!traversedInterfaces.contains(c)) &#123;</span><br><span class="line">                traversedInterfaces.add(c);</span><br><span class="line">                <span class="comment">// 递归方式 对父类接口字段获取</span></span><br><span class="line">                addAll(fields, c.privateGetPublicFields(traversedInterfaces));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3.Direct superclass, recursively</span></span><br><span class="line">        <span class="keyword">if</span> (!isInterface()) &#123;</span><br><span class="line">            <span class="comment">// 不是接口 走该判断</span></span><br><span class="line">            Class&lt;?&gt; c = getSuperclass();</span><br><span class="line">            <span class="keyword">if</span> (c != <span class="keyword">null</span>) &#123;</span><br><span class="line">                addAll(fields, c.privateGetPublicFields(traversedInterfaces));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        res = <span class="keyword">new</span> Field[fields.size()];</span><br><span class="line">        fields.toArray(res);</span><br><span class="line">        <span class="keyword">if</span> (rd != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 缓存共有字段</span></span><br><span class="line">            rd.publicFields = res;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>ReflectionData缓存:    volatile软引用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Reflection support.</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">// Caches for certain reflective results  反射结果是否缓存</span></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> useCaches = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// reflection data that might get invalidated when JVM TI RedefineClasses() is called</span></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ReflectionData</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">       <span class="keyword">volatile</span> Field[] declaredFields; <span class="comment">// 声明的字段(本类的)</span></span><br><span class="line">       <span class="keyword">volatile</span> Field[] publicFields; <span class="comment">// 公开的字段(包括继承和接口的)</span></span><br><span class="line">       <span class="keyword">volatile</span> Method[] declaredMethods;</span><br><span class="line">       <span class="keyword">volatile</span> Method[] publicMethods;</span><br><span class="line">       <span class="keyword">volatile</span> Constructor&lt;T&gt;[] declaredConstructors;</span><br><span class="line">       <span class="keyword">volatile</span> Constructor&lt;T&gt;[] publicConstructors;</span><br><span class="line">       <span class="comment">// Intermediate results for getFields and getMethods</span></span><br><span class="line">       <span class="keyword">volatile</span> Field[] declaredPublicFields;</span><br><span class="line">       <span class="keyword">volatile</span> Method[] declaredPublicMethods;</span><br><span class="line">       <span class="keyword">volatile</span> Class&lt;?&gt;[] interfaces;</span><br><span class="line"></span><br><span class="line">       <span class="comment">// Value of classRedefinedCount when we created this ReflectionData instance</span></span><br><span class="line">       <span class="keyword">final</span> <span class="keyword">int</span> redefinedCount;</span><br><span class="line"></span><br><span class="line">       ReflectionData(<span class="keyword">int</span> redefinedCount) &#123;</span><br><span class="line">           <span class="keyword">this</span>.redefinedCount = redefinedCount;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Lazily create and cache ReflectionData</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> ReflectionData&lt;T&gt; <span class="title">reflectionData</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        SoftReference&lt;ReflectionData&lt;T&gt;&gt; reflectionData = <span class="keyword">this</span>.reflectionData;</span><br><span class="line">        <span class="keyword">int</span> classRedefinedCount = <span class="keyword">this</span>.classRedefinedCount;</span><br><span class="line">        ReflectionData&lt;T&gt; rd;</span><br><span class="line">        <span class="keyword">if</span> (useCaches &amp;&amp;</span><br><span class="line">            reflectionData != <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">            (rd = reflectionData.get()) != <span class="keyword">null</span> &amp;&amp;</span><br><span class="line">            rd.redefinedCount == classRedefinedCount) &#123;</span><br><span class="line">            <span class="keyword">return</span> rd;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// else no SoftReference or cleared SoftReference or stale ReflectionData</span></span><br><span class="line">        <span class="comment">// -&gt; create and replace new instance</span></span><br><span class="line">        <span class="keyword">return</span> newReflectionData(reflectionData, classRedefinedCount);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h5 id="2、【class-newInstance-】、【class-getConstructor-】-【class-getDeclaredConstructor-】"><a href="#2、【class-newInstance-】、【class-getConstructor-】-【class-getDeclaredConstructor-】" class="headerlink" title="2、【class.newInstance() 】、【class.getConstructor()】\ 【class.getDeclaredConstructor()】"></a>2、【class.newInstance() 】、【class.getConstructor()】\ 【class.getDeclaredConstructor()】</h5><blockquote>
<p>如何借助反射创建对象?</p>
<p>getConstructor()与getDeclaredConstructor()区别？</p>
</blockquote>
<ul>
<li><strong>1）class.newInstance()  </strong></li>
</ul>
<p>通过类对象调用创建。 <strong>适用于无参构造方法</strong></p>
<p>String.class.newInstance()</p>
<ul>
<li><strong>2）class.getConstructor()  </strong></li>
</ul>
<p>通过类对象调用获得构造器对象(Constructor),再借助Constructor调用newInstance()达成创建。<strong>适用于无参/有参构造方法。</strong></p>
<p>String.class.getConstructor(String.class).newInstance(“o.o”);</p>
<ul>
<li><strong>3）getConstructor() / getDeclaredContrudctor() 区别</strong></li>
</ul>
<p>getConstructor(Class&lt;?&gt;… parameterTypes)     获取制定参数类型的访问权限是public的构造器</p>
<p>getDeclaredConstructor(Class&lt;?&gt;… parameterTypes)    获取制定参数类型的所有已声明的构造器(包括private)</p>
<p><strong>疑问：</strong>为什么通过先获取Constructor再调用newInstance()可以达成有参构造？</p>
<p>=&gt; 区分newInstance()，class类中的newInstance()与Constructor()的newInstance()实现逻辑不一样。</p>
<p><strong>Class.newInstance()：</strong>仅贴出主流程部分关键源码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">newInstance</span><span class="params">()</span></span></span><br><span class="line"><span class="function">       <span class="keyword">throws</span> InstantiationException, IllegalAccessException</span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">	Class&lt;?&gt;[] empty = &#123;&#125;;</span><br><span class="line">	<span class="comment">// 获取构造器对象</span></span><br><span class="line">	<span class="keyword">final</span> Constructor&lt;T&gt; c = getConstructor0(empty, Member.DECLARED);</span><br><span class="line">	<span class="comment">// 缓存</span></span><br><span class="line">	cachedConstructor = c;</span><br><span class="line">	<span class="comment">// 构造器对象</span></span><br><span class="line">	Constructor&lt;T&gt; tmpConstructor = cachedConstructor;</span><br><span class="line">	<span class="comment">// 通过构造器的newInstance()创建对象		</span></span><br><span class="line">	<span class="keyword">return</span> tmpConstructor.newInstance((Object[])<span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>Class.getConstructor</strong>:    返回访问权限是public的构造器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CallerSensitive</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Constructor&lt;T&gt; <span class="title">getConstructor</span><span class="params">(Class&lt;?&gt;... parameterTypes)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> NoSuchMethodException, SecurityException </span>&#123;</span><br><span class="line">        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), <span class="keyword">true</span>);</span><br><span class="line">        <span class="comment">// public static final int PUBLIC = 0; 返回访问权限是public的构造器</span></span><br><span class="line">        <span class="keyword">return</span> getConstructor0(parameterTypes, Member.PUBLIC);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><strong>Class.getDeclaredConstructor:</strong>    返回所有声明的构造器(包括private)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CallerSensitive</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Constructor&lt;T&gt; <span class="title">getDeclaredConstructor</span><span class="params">(Class&lt;?&gt;... parameterTypes)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> NoSuchMethodException, SecurityException </span>&#123;</span><br><span class="line">        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), <span class="keyword">true</span>);</span><br><span class="line">        <span class="comment">// public static final int DECLARED = 1; 返回所有声明的构造器(包括private)</span></span><br><span class="line">        <span class="keyword">return</span> getConstructor0(parameterTypes, Member.DECLARED);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><strong>Constructor.newInstance:</strong>    构造器类的newInstance()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">newInstance</span><span class="params">(Object ... initargs)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> InstantiationException, IllegalAccessException,</span></span><br><span class="line"><span class="function">               IllegalArgumentException, InvocationTargetException</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!override) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!Reflection.quickCheckMemberAccess(clazz, modifiers)) &#123;</span><br><span class="line">                Class&lt;?&gt; caller = Reflection.getCallerClass();</span><br><span class="line">                checkAccess(caller, clazz, <span class="keyword">null</span>, modifiers);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> ((clazz.getModifiers() &amp; Modifier.ENUM) != <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Cannot reflectively create enum objects"</span>);</span><br><span class="line">        ConstructorAccessor ca = constructorAccessor;   <span class="comment">// read volatile</span></span><br><span class="line">        <span class="keyword">if</span> (ca == <span class="keyword">null</span>) &#123;</span><br><span class="line">            ca = acquireConstructorAccessor();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">        T inst = (T) ca.newInstance(initargs);</span><br><span class="line">        <span class="keyword">return</span> inst;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><strong>Class.getConstructor0:</strong>    </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Constructor&lt;T&gt; <span class="title">getConstructor0</span><span class="params">(Class&lt;?&gt;[] parameterTypes,</span></span></span><br><span class="line"><span class="function"><span class="params">                                        <span class="keyword">int</span> which)</span> <span class="keyword">throws</span> NoSuchMethodException</span></span><br><span class="line"><span class="function">    </span>&#123;	</span><br><span class="line">    	<span class="comment">// 传入的which带有权限信息 通过which==Member.PUBLIC =&gt; 确定获取数据的范围</span></span><br><span class="line">        Constructor&lt;T&gt;[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));</span><br><span class="line">        <span class="keyword">for</span> (Constructor&lt;T&gt; constructor : constructors) &#123;</span><br><span class="line">            <span class="keyword">if</span> (arrayContentsEq(parameterTypes,</span><br><span class="line">                                constructor.getParameterTypes())) &#123;</span><br><span class="line">                <span class="keyword">return</span> getReflectionFactory().copyConstructor(constructor);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchMethodException(getName() + <span class="string">".&lt;init&gt;"</span> + argumentTypesToString(parameterTypes));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Returns an array of "root" constructors. These Constructor</span></span><br><span class="line">   <span class="comment">// objects must NOT be propagated to the outside world, but must</span></span><br><span class="line">   <span class="comment">// instead be copied via ReflectionFactory.copyConstructor.</span></span><br><span class="line">   <span class="keyword">private</span> Constructor&lt;T&gt;[] privateGetDeclaredConstructors(<span class="keyword">boolean</span> publicOnly) &#123;</span><br><span class="line">       checkInitted();</span><br><span class="line">       Constructor&lt;T&gt;[] res;</span><br><span class="line">       ReflectionData&lt;T&gt; rd = reflectionData();</span><br><span class="line">       <span class="keyword">if</span> (rd != <span class="keyword">null</span>) &#123;</span><br><span class="line">           res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;</span><br><span class="line">           <span class="keyword">if</span> (res != <span class="keyword">null</span>) <span class="keyword">return</span> res;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="comment">// No cached value available; request value from VM</span></span><br><span class="line">       <span class="keyword">if</span> (isInterface()) &#123;</span><br><span class="line">           <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">           Constructor&lt;T&gt;[] temporaryRes = (Constructor&lt;T&gt;[]) <span class="keyword">new</span> Constructor&lt;?&gt;[<span class="number">0</span>];</span><br><span class="line">           res = temporaryRes;</span><br><span class="line">       &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">           res = getDeclaredConstructors0(publicOnly);</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">if</span> (rd != <span class="keyword">null</span>) &#123;</span><br><span class="line">           <span class="keyword">if</span> (publicOnly) &#123;</span><br><span class="line">               rd.publicConstructors = res;</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">               rd.declaredConstructors = res;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> res;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
    </div>
    <p class="post-meta">
        <span class="post-cat">分类：
            <a class="cat-link" href="/categories/technology/">technology</a>
        </span>
        <span class="post-tags">
            标签：
            
    
        <a href="/tags/源码学习/" title="源码学习">源码学习</a>
    

        </span>
    </p>
</article>
<!-- 分享按钮 -->

  <div class="article-share clearfix text-center">
    <div class="share-area">
      <span class="share-txt">分享到：</span>
      <a href="javascript: window.open('http://service.weibo.com/share/share.php?url=' + encodeURIComponent(location.href) + '&title=' + document.title + '&language=zh_cn');" class="share-icon weibo"></a>
      <a href="javascript: alert('请复制链接到微信并发送');" class="share-icon wechat"></a>
      <a href="javascript: window.open('http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent(location.href) + '&title=' + document.title);" class="share-icon qqzone"></a>
      <a href="javascript: window.open('http://connect.qq.com/widget/shareqq/index.html?url=' + encodeURIComponent(location.href) + '&desc=Jim个人博客&title=' + document.title + '&callback=' + encodeURIComponent(location.href));" class="share-icon qq"></a>
      <a href="javascript: window.open('http://shuo.douban.com/!service/share?href=' + encodeURIComponent(location.href) + '&name=' + document.title + '&text=' + document.title);" class="share-icon douban"></a>
    </div>
  </div>


<!-- 上一篇/下一篇 -->

<div class="article-nav clearfix">
    
    <span class="prev fl">
        上一篇<br>
        <a href="/2019/07/11/Proxy-InvocationHandler源码学习/">
            
                Proxy / InvocationHandler源码学习
            
        </a>
    </span>
    

    
    <span class="next fr">
        下一篇<br>
        <a href="/2019/07/11/design_pattern_代理模式/">
            
                代理模式
            
        </a>
    </span>
    
</div>

<!-- 文章评论 -->

  <script src="/js/comment.js"></script>
  <div id="comments" class="comment">
    <!--
    <div class="sign-bar">
      GitHub 已登录!
      <span class="sign-link">登出</span>
    </div>
    <section class="box">
      <div class="com-avatar"><img src="/img/jelon.jpg" alt="avatar"></div>
      <div class="com-text">
        <div class="main">
          <textarea class="text-area-edited show" placeholder="欢迎评论！"></textarea>
          <div class="text-area-preview"></div>
        </div>
        <div class="switch">
          <div class="switch-item on">编辑</div>
          <div class="switch-item">预览</div>
        </div>
        <div class="button">提交</div>
      </div>
    </section>
    <section class="tips">注：评论支持 markdown 语法！</section>
    <section class="list-wrap">
      <ul class="list">
        <li>
          <div class="user-avatar">
            <a href="/">
              <img src="/img/jelon.jpg" alt="user-avatar">
            </a>
          </div>
          <div class="user-comment">
            <div class="user-comment-header">
              <span class="post-name">张德龙</span>
              <span class="post-time">2017年12月12日</span>
              <span class="like liked">已赞</span>
              <span class="like-num">2</span>
            </div>
            <div class="user-comment-body">333333</div>
          </div>
        </li>
        <li>
          <div class="user-avatar">
            <a href="/">
              <img src="/img/jelon.jpg" alt="user-avatar">
            </a>
          </div>
          <div class="user-comment">
            <div class="user-comment-header">
              <span class="post-name">刘德华</span>
              <span class="post-time">2017年12月12日</span>
              <span class="like">点赞</span>
              <span class="like-num">2</span>
            </div>
            <div class="user-comment-body">vvvvv</div>
          </div>
        </li>
      </ul>
      <div class="page-nav">
        <a href="javascript: void(0);" class="item">1</a>
        <a href="javascript: void(0);" class="item">2</a>
        <a href="javascript: void(0);" class="item current">3</a>
      </div>
    </section>
    -->
  </div>
  <script>
  JELON.Comment({
    container: 'comments',
    label: 'Class源码' || '2019/07/11/Class源码/',
    owner: 'your_github_id',
    repo: 'your_blog_comments',
    clientId: 'your_client_id',
    clientSecret: 'your_client_secret'
  });
  </script>


            </div>

        </section>
        <!-- 侧栏部分 -->
<aside class="sidebar">
    <section class="widget">
        <h3 class="widget-hd"><strong>文章分类</strong></h3>
        <!-- 文章分类 -->
<ul class="widget-bd">
    
    <li>
        <a href="/categories/linus/">linus</a>
        <span class="badge">(4)</span>
    </li>
    
    <li>
        <a href="/categories/technology/">technology</a>
        <span class="badge">(8)</span>
    </li>
    
    <li>
        <a href="/categories/Reading/">Reading</a>
        <span class="badge">(13)</span>
    </li>
    
    <li>
        <a href="/categories/others/">others</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/categories/linus/technology/">technology</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/categories/mysql/">mysql</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/categories/mysql/technology/">technology</a>
        <span class="badge">(1)</span>
    </li>
    
</ul>
    </section>

    
    <section class="widget">
        <h3 class="widget-hd"><strong>热门标签</strong></h3>
        <!-- 文章标签 -->
<div class="widget-bd tag-wrap">
  
    <a class="tag-item" href="/tags/linus/" title="linus">linus (4)</a>
  
    <a class="tag-item" href="/tags/ngnix/" title="ngnix">ngnix (1)</a>
  
    <a class="tag-item" href="/tags/源码学习/" title="源码学习">源码学习 (2)</a>
  
    <a class="tag-item" href="/tags/阅读/" title="阅读">阅读 (13)</a>
  
    <a class="tag-item" href="/tags/Thinking-In-Java/" title="Thinking In Java">Thinking In Java (5)</a>
  
    <a class="tag-item" href="/tags/java/" title="java">java (3)</a>
  
    <a class="tag-item" href="/tags/technology/" title="technology">technology (1)</a>
  
    <a class="tag-item" href="/tags/springBoot/" title="springBoot">springBoot (2)</a>
  
    <a class="tag-item" href="/tags/设计模式/" title="设计模式">设计模式 (3)</a>
  
    <a class="tag-item" href="/tags/test/" title="test">test (1)</a>
  
    <a class="tag-item" href="/tags/Effective-Java/" title="Effective Java">Effective Java (8)</a>
  
    <a class="tag-item" href="/tags/mysql/" title="mysql">mysql (2)</a>
  
    <a class="tag-item" href="/tags/Docker/" title="Docker">Docker (1)</a>
  
</div>
    </section>
    

    

    
    <!-- 友情链接 -->
    <section class="widget">
        <h3 class="widget-hd"><strong>友情链接</strong></h3>
        <!-- 文章分类 -->
<ul class="widget-bd">
    
        <li>
            <a href="https://www.bilibili.com" target="_blank" title="bilibili">哔哩哔哩</a>
        </li>
    
        <li>
            <a href="https://www.baidu.com" target="_blank" title="百度搜索">百度</a>
        </li>
    
</ul>
    </section>
    
</aside>
<!-- / 侧栏部分 -->
    </div>

    <!-- 博客底部 -->
    <footer class="footer">
    &copy;
    
        2016-2020
    

    <a href="/">Jim Loves You</a>
</footer>
<div class="back-to-top" id="JELON__backToTop" title="返回顶部">返回顶部</div>

    <!--博客js脚本 -->
    <!-- 这里放网站js脚本 -->
<script src="/js/main.js"></script>
</body>
</html>